<template>
  <div>
    <el-dialog title="订单详情" :visible.sync="show" width="1200px" :close-on-click-modal="false" :before-close="cancel">
      <el-form ref="queryForm" class="supplierOrderDetail"
               :model="form"
               :rules="rules"
               inline
               size="mini"
               label-width="100px"
               :show-message="detail.status == 1"
               v-if="detail">
        <el-alert :closable="false" title="订单信息"/>
        <el-row class="mt5">
          <el-col :span="8">
            <el-form-item label="订单金额：">￥{{ detail.totalMoney }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单编号：">{{ detail.orderNo }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单状态：">{{ detail.statusText }}</el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="下单时间：">{{ detail.createTime }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注：">{{ detail.remark || '--' }}</el-form-item>
          </el-col>
          <el-col :span="8" v-if="detail.cancelRemark">
            <el-form-item label="拒绝备注：">{{ detail.cancelRemark || '--' }}</el-form-item>
          </el-col>
        </el-row>
        <el-alert :closable="false" title="收货信息"/>
        <el-row class="mt5">
          <el-col :span="8">
            <el-form-item label="收货门店：">{{ detail.shopName }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收货人：">{{ detail.contact }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式：">{{ detail.contactPhone }}</el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收货时间：">{{ detail.inStockTime || '未收货' }}</el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="收货地址：">{{ detail.address}}</el-form-item>
          </el-col>
        </el-row>
        <el-alert :closable="false" title="配送信息"/>
        <el-row class="mt5">
          <el-col :span="8">
            <el-form-item label="配送人：" prop="deliveryContact">
              <el-input v-model="form.deliveryContact" placeholder="请输入配送人姓名" v-if="detail.status == 1"/>
              <span v-else>{{detail.deliveryContact || '--' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系方式：" prop="deliveryPhone">
              <el-input v-model="form.deliveryPhone" placeholder="请输入配送人联系方式" v-if="detail.status == 1" maxlength="11"/>
              <span v-else>{{detail.deliveryPhone || '--' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="配送时间：">{{detail.deliveryTime || '未发货'}}</el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="配送备注：">
              <el-input type="textarea" v-model="form.deliveryRemark" aria-placeholder="请输入配送备注" v-if="detail.status == 1"/>
              <span v-else>{{ detail.deliveryRemark || '--' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-alert :closable="false" title="商品信息"/>
        <el-row class="mt10">
          <el-col>
            <el-table :data="goodsList" :summary-method="getSummaries" show-summary :key="tableKey" max-height="500px">
              <el-table-column label="序号" type="index" :index="(index) => index+1"/>
              <el-table-column label="商品名称" prop="name"/>
              <el-table-column label="进价(元)" align="center" prop="purchaseTotalPrice" width="80px">
                <template slot-scope="scope">
                  {{ scope.row.purchaseTotalPrice }}/{{ scope.row.restockUnit }}
                </template>
              </el-table-column>
              <el-table-column label="规格" align="center">
                <template slot-scope="scope">
                  {{ scope.row.stockConversion }}{{ scope.row.unit }}
                </template>
              </el-table-column>
              <el-table-column label="进货单位" align="center" prop="restockUnit" width="80px"/>
              <el-table-column label="分类" align="center">
                <template slot-scope="scope">
                  {{ scope.row.firstTypeName }} / {{ scope.row.secondTypeName }}
                </template>
              </el-table-column>
              <el-table-column label="预采购数量" prop="number" align="center" width="100px"/>
              <el-table-column label="预采购金额" align="center" prop="totalMoney" width="100px"/>
              <el-table-column label="实际发货数量" align="center" prop="deliveryNumber" width="100px">
                <template slot-scope="scope">
                  <template v-if="detail.status == 1">
                    <el-input-number size="mini"
                                     v-model="scope.row.deliveryNumber"
                                     :min="0"
                                     :precision="0"
                                     style="width: 80px"
                                     :controls="false"
                                     @change="calcMoney(scope.row, $event, scope.$index)"/>
                  </template>
                  <template v-else>{{ scope.row.deliveryNumber }}</template>
                </template>
              </el-table-column>
              <el-table-column label="实际发货金额" align="center" prop="actualMoney" width="100px" v-if="detail.status < 3"/>
              <template v-else-if="detail.status == 3">
                <el-table-column label="实际收货数量" align="center" prop="receiveNumber" width="100px"/>
                <el-table-column label="实际收货金额" align="center" prop="actualMoney" width="100px"/>
              </template>
            </el-table>
            <div class="flex align-top mt20" v-if="detail.imageUrl">
              <div class="mr5">货单：</div>
              <el-image :src="detail.imageUrl" :preview-src-list="[detail.imageUrl]" style="width: 80px;height: 80px"></el-image>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="default" @click="cancel" size="small">关闭</el-button>
        <el-button type="primary" @click="submit" size="small" :loading="submitLoading" v-if="detail.status == 1">发货</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {orderDetail, orderDelivery} from '@/api/order'
import {mapGetters} from "vuex";

export default {
  name: "procurementForm",
  props: {
    value: false,
    id: '',
    supplierList: {
      type: Array, default: () => {
        return []
      }
    }
  },
  data() {
    return {
      tableKey: '',
      detail: '',
      form: {
        deliveryContact: '',
        deliveryPhone: ''
      },
      rules: {
        deliveryContact: [
          {required: true, message: '请输入配送人姓名', trigger: 'change'}
        ],
        deliveryPhone: [
          {required: true, message: '请输入配送人联系方式', trigger: 'change'},
          {pattern: /^1[34578]\d{9}$/, message: '请输入正确的联系方式', trigger: 'change'}
        ]
      },
      goodsList: [],
      submitLoading: false
    }
  },
  computed: {
    show: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    },
    ...mapGetters(['sysUserId'])
  },
  mounted() {
  },
  methods: {
    getDetail() {
      this.detail = ''
      orderDetail(this.id).then(res => {
        this.detail = res.data
        this.goodsList = res.data.goodsList
        this.goodsList.map(item => {
          item.unit = item.unit == item.inStockUnit ? item.unit : (item.unit +'/'+ item.inStockUnit)
          if (this.detail.status < 2) {
            item.deliveryNumber = item.number;
          }
          if (this.detail.status < 3) {
            item.actualMoney = (item.purchaseTotalPrice * item.deliveryNumber).toFixed(2)
          }
        })
      })
    },
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value)) && ['totalMoney', 'actualMoney'].indexOf(column.property) >= 0) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] = (sums[index]).toFixed(2) + ' 元';
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },
    calcMoney(row, e, index) {
      if (!e) return
      const price = row.restockType == 1 ? row.purchasePrice : row.purchaseTotalPrice
      row.actualMoney = (price * e).toFixed(2)
      this.$set(this.goodsList, index, row)
    },
    cancel() {
      this.show = false
      this.form = {
        deliveryContact: '',
        deliveryPhone: ''
      }
    },
    submit() {
      this.$refs.queryForm.validate(valid => {
        if (!valid) return
        this.form.goodsList = this.goodsList.map(item => {
          return {
            id: item.id,
            goodsId: item.goodsId,
            deliveryNumber: item.deliveryNumber || 0
          }
        })
        let isNull = this.form.goodsList.findIndex(item => item == null)
        if (isNull >= 0) return
        this.form.id = this.id
        if (this.submitLoading) return;
        this.submitLoading = true
        orderDelivery(this.form).then(res => {
          if (res.code == 200) {
            this.$emit('success')
            this.$message.success('提交成功')
            localStorage.setItem('supplierContact'+this.sysUserId, JSON.stringify({
              contact: this.form.deliveryContact,
              phone: this.form.deliveryPhone
            }))
            this.cancel()
          }
        }).finally(() => {
          this.submitLoading = false
        })
      })
    }
  },
  watch: {
    show() {
      if (this.show) {
        let supplierContact = localStorage.getItem('supplierContact'+this.sysUserId)
        if (supplierContact) {
          supplierContact = JSON.parse(supplierContact)
          this.form.deliveryContact = supplierContact.contact
          this.form.deliveryPhone = supplierContact.phone
        }
        this.getDetail()
      }
    }
  }
}
</script>

<style lang="less">
.supplierOrderDetail {
  .el-form-item {
    margin-bottom: 15px!important;
  }
}
</style>
